package config.security;

import io.jsonwebtoken.Claims;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.security.web.server.context.ServerSecurityContextRepository;
import org.springframework.security.web.server.context.WebSessionServerSecurityContextRepository;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.List;

//@Component
public class MyServerSecurityContextRepository implements ServerSecurityContextRepository {
    public static final String Bearer = "Bearer ";

    @Override
    public Mono<Void> save(ServerWebExchange exchange, SecurityContext context) {
        return exchange.getSession()
                .doOnNext(session -> {
                    if (context == null) {
                        session.getAttributes().remove(WebSessionServerSecurityContextRepository.DEFAULT_SPRING_SECURITY_CONTEXT_ATTR_NAME);
                    } else {
                        session.getAttributes().put(WebSessionServerSecurityContextRepository.DEFAULT_SPRING_SECURITY_CONTEXT_ATTR_NAME, context);
                    }
                })
                .flatMap(session -> session.changeSessionId());
    }

//    @Autowired
//    private MyAuthenticationManager authenticationManager;

    @Override
    public Mono<SecurityContext> load(ServerWebExchange exchange) {
        ServerHttpRequest request = exchange.getRequest();
        String authenticationHeader = request.getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
        if (authenticationHeader != null && authenticationHeader.startsWith(Bearer)) {
            String token = authenticationHeader.replace(Bearer, "");
//
            Claims claimFromToken = JwtTokenUtil.getClaimFromToken(token);
            if (claimFromToken != null) {
                String username = (String) claimFromToken.get(JwtTokenUtil.CLAIM_KEY_USERNAME);
//                List o = (List) claimFromToken.get(JwtTokenUtil.CLAIM_KEY_ROLES);
                List<SimpleGrantedAuthority> list = new ArrayList<>();

                ((List) claimFromToken.get(JwtTokenUtil.CLAIM_KEY_ROLES)).forEach(e -> {
                    list.add(new SimpleGrantedAuthority((String) e));
                });
//                return Mono.just(new UsernamePasswordAuthenticationToken(username, username, o1));
//                SecurityContextHolder.getContext().setAuthentication(new AuthenticatedUser(username, list));
//                ReactiveSecurityContextHolder.getContext()
//                        .subscriberContext(ReactiveSecurityContextHolder.withAuthentication(new AuthenticatedUser(username, list)));
//                ReactiveSecurityContextHolder.withSecurityContext()
//                SecurityContext securityContext = new SecurityContextImpl();
//                securityContext.setAuthentication(new UsernamePasswordAuthenticationToken(username, username, list));
                SecurityContextImpl securityContext = new SecurityContextImpl(new UsernamePasswordAuthenticationToken(username, username, list));
                this.save(exchange, securityContext);
                return Mono.just(securityContext);
            }

            return Mono.empty();
        }
        return Mono.empty();
    }

}
